package com.buptlogistics.creditinvestigation.fragment;


import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.buptlogistics.creditinvestigation.R;
import com.buptlogistics.creditinvestigation.activity.CommonActivity;
import com.buptlogistics.creditinvestigation.activity.LoginRegistActivity;
import com.buptlogistics.creditinvestigation.app.AppData;
import com.buptlogistics.creditinvestigation.app.BaseFragment;
import com.buptlogistics.creditinvestigation.entity.User;
import com.buptlogistics.creditinvestigation.utils.Logcat;
import com.buptlogistics.creditinvestigation.utils.ResultUtils;
import com.buptlogistics.creditinvestigation.window.SelectPicPopupWindow;

import java.io.ByteArrayOutputStream;
import java.net.URL;

/**
 * A simple {@link Fragment} subclass.
 */
public class AccountFragment extends BaseFragment {

    private ImageView iv_head;
    private View view;
    private TextView tv_account_loan;
    private TextView tv_account_logistics;
    private TextView tv_account_receipt;
    private TextView tv_account_company;
    private TextView tv_account_credit;
    private TextView tv_account_bill;
    private TextView tv_account_name;

    private LinearLayout ll_account_loan;
    private LinearLayout ll_account_logistics;
    private LinearLayout ll_account_receipt;
    private LinearLayout ll_account_company;
    private LinearLayout ll_account_credit;
    private LinearLayout ll_account_bill;
    private LinearLayout ll_account_name;
    private LinearLayout ll_account_alert;
    private LinearLayout ll_account_my_count;

    // 自定义的弹出框类
    SelectPicPopupWindow menuWindow;
    Bitmap bmp;
    Bitmap photo;
    ResultUtils result;

    //private final File tempFile = new File(
    //        Environment.getExternalStorageDirectory(), getPhotoFileName());

    public AccountFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_account, container, false);
        initViews();
        initEvents();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    protected void initViews() {
        iv_head = (ImageView) findViewById(R.id.iv_account_head);
        tv_account_loan = (TextView) findViewById(R.id.tv_account_loan);
        tv_account_logistics = (TextView) findViewById(R.id.tv_account_logistics);
        tv_account_receipt = (TextView) findViewById(R.id.tv_account_receipt);
        tv_account_company = (TextView) findViewById(R.id.tv_account_company);
        tv_account_credit = (TextView) findViewById(R.id.tv_account_credit);
        tv_account_bill = (TextView) findViewById(R.id.tv_account_bill);
        tv_account_name = (TextView) findViewById(R.id.tv_account_name);
        ll_account_loan = (LinearLayout) findViewById(R.id.ll_account_loan);
        ll_account_logistics = (LinearLayout) findViewById(R.id.ll_account_logistics);
        ll_account_receipt = (LinearLayout) findViewById(R.id.ll_account_receipt);
        ll_account_company = (LinearLayout) findViewById(R.id.ll_account_company);
        ll_account_credit = (LinearLayout) findViewById(R.id.ll_account_credit);
        ll_account_bill = (LinearLayout) findViewById(R.id.ll_account_bill);
        ll_account_alert = (LinearLayout) findViewById(R.id.ll_account_bill_alert);
        ll_account_my_count = (LinearLayout) findViewById(R.id.ll_account_my_count);

    }

    private void initData() {
        if (AppData.getInstance(AccountFragment.this.getActivity()).getIsLogin()) {
            if (AppData.getInstance(AccountFragment.this.getActivity()).getUserInfo
                    ().equals("")) {
                Log.e("avuser","null user");
                return;
            }else{
                User user = JSON.parseObject(AppData.getInstance(AccountFragment.this.getActivity()).getUserInfo
                        (), User.class);
                Logcat.i("user", user.toString());
                tv_account_name.setText(user.getUserName());
            }

        } else {
            tv_account_name.setText("未登录");
        }
    }

    protected void initEvents() {
        iv_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!AppData.getInstance(AccountFragment.this.getActivity()).getIsLogin()) {
                    startActivity(LoginRegistActivity.class);
                } else {
                    // 实例化SelectPicPopupWindow
                    menuWindow = new SelectPicPopupWindow(AccountFragment.this.getActivity(),
                            itemsOnClick);
                    // 显示窗口
                    menuWindow.showAtLocation(AccountFragment.this.getActivity()
                            .findViewById(R.id.ll_account), Gravity.BOTTOM
                            | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                }
            }
        });
        ll_account_loan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle data = new Bundle();
                data.putInt("fragmentType", 12);
                // 创建一个Intent
                Intent intent = new Intent(AccountFragment.this.getActivity(),
                        CommonActivity.class);
                intent.putExtras(data);
                // 启动intent对应的Activity
                startActivity(intent);
            }
        });
        ll_account_logistics.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle data = new Bundle();
                data.putInt("fragmentType", 13);
                // 创建一个Intent
                Intent intent = new Intent(AccountFragment.this.getActivity(),
                        CommonActivity.class);
                intent.putExtras(data);
                // 启动intent对应的Activity
                startActivity(intent);
            }
        });
        ll_account_receipt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle data = new Bundle();
                data.putInt("fragmentType", 14);
                // 创建一个Intent
                Intent intent = new Intent(AccountFragment.this.getActivity(),
                        CommonActivity.class);
                intent.putExtras(data);
                // 启动intent对应的Activity
                startActivity(intent);
            }
        });
        ll_account_company.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle data = new Bundle();
                data.putInt("fragmentType", 15);
                // 创建一个Intent
                Intent intent = new Intent(AccountFragment.this.getActivity(),
                        CommonActivity.class);
                intent.putExtras(data);
                // 启动intent对应的Activity
                startActivity(intent);
            }
        });
        ll_account_credit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle data = new Bundle();
                data.putInt("fragmentType", 16);
                // 创建一个Intent
                Intent intent = new Intent(AccountFragment.this.getActivity(),
                        CommonActivity.class);
                intent.putExtras(data);
                // 启动intent对应的Activity
                startActivity(intent);
            }
        });
        ll_account_bill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle data = new Bundle();
                data.putInt("fragmentType", 17);
                // 创建一个Intent
                Intent intent = new Intent(AccountFragment.this.getActivity(),
                        CommonActivity.class);
                intent.putExtras(data);
                // 启动intent对应的Activity
                startActivity(intent);
            }
        });
        ll_account_alert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle data = new Bundle();
                data.putInt("fragmentType", 11);
                // 创建一个Intent
                Intent intent = new Intent(AccountFragment.this.getActivity(),
                        CommonActivity.class);
                intent.putExtras(data);
                // 启动intent对应的Activity
                startActivity(intent);
            }
        });
    }

    //@Override
    //public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //    super.onActivityResult(requestCode, resultCode, data);
    //    if (requestCode == 100) {
    //        startPhotoZoom(Uri.fromFile(tempFile));
    //    } else if ((requestCode == 101) && (data != null)) {
    //        startPhotoZoom(data.getData());
    //    } else if ((requestCode == 102) && (data != null)) {
    //        sentPicToNext(data);
    //    }
    //
    //}

    /**
     * 照片剪裁
     */
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 102);
    }

//    /**
//     * 将进行剪裁后的图片传递到下一个界面上
//     */
//    private void sentPicToNext(Intent picdata) {
//        Bundle bundle = picdata.getExtras();
//        if (bundle != null) {
//            photo = bundle.getParcelable("data");
//            if (photo == null) {
//                iv_head.setImageResource(R.drawable.ic_launcher);
//            } else {
//                iv_head.setImageBitmap(photo);
//            }
//            Toast.makeText(AccountFragment.this.getActivity(),
//                    "正在上传头像，请您稍后操作！", Toast.LENGTH_LONG).show();
//            //另开线程上传头像
//            new Thread() {
//                public void run() {
//                    // 图片上传
//                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                    // 将bitmap一字节流输出 Bitmap.CompressFormat.PNG
//                    // 压缩格式，100：压缩率，baos：字节流
//                    photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
//                    byte[] bs = baos.toByteArray();
//                    char[] digital = "0123456789ABCDEF".toCharArray();
//                    StringBuilder sb = new StringBuilder("");
//                    int bit;
//                    for (int i = 0; i < bs.length; i++) {
//                        bit = (bs[i] & 0x0f0) >> 4;
//                        sb.append(digital[bit]);
//                        bit = bs[i] & 0x0f;
//                        sb.append(digital[bit]);
//                    }
//                    String photodata = sb.toString();
//                    if (photodata != null) {
//                        String ext = "png";
//                        String filename = DateFormat.format("yyyyMMdd_hhmmss",
//                                Calendar.getInstance(Locale.CHINA)) + ".png";
//                        IcyBeeUtil.setUserHead(AppData.getInstance(AccountFragment.this.getActivity())
//                                .getTooken(), );
//                        if (result != null) {
//                            if (result.getStatus() == 200) {
//                                Message msg = new Message();
//                                msg.what = 2;
//                                bitMapHander.sendMessage(msg);
////								Toast.makeText(InformationActivity.this,
////										"上传头像成功！", Toast.LENGTH_SHORT).show();
////								try {
////									JSONObject userJson = new JSONObject(
////											result.getData());
////									CacheUrlPicture.downloadPicture(
////											userJson.getString("avatar"), InformationActivity.this,
////											false);
////
////									CacheUrlPicture.downloadPicture(
////											userJson.getString("avatar_big"),
////											InformationActivity.this, true);
////								} catch (Exception e) {
////									e.printStackTrace();
////								}
//                            } else {
//                                Message msg = new Message();
//                                msg.what = 3;
//                                bitMapHander.sendMessage(msg);
////								Toast.makeText(InformationActivity.this,
////										"上传头像失败！", Toast.LENGTH_SHORT).show();
////								Log.i(ACTIVITY_TAG, result.getStatus() + "   "
////										+ result.getMessage());
//                            }
//                        } else {
//                            Message msg = new Message();
//                            msg.what = 4;
//                            bitMapHander.sendMessage(msg);
////							new AlertDialog.Builder(InformationActivity.this)
////									.setMessage("访问服务异常")
////									.setPositiveButton("确定", null).show();
//                        }
//                    }
//
//                }
//            }.start();
//        }
//    }


    //private final Handler bitMapHander = new Handler() {
    //    @Override
    //    public void handleMessage(Message msg) {
    //
    //        if (msg.what == 1) {
    //            iv_head.setImageBitmap(bmp);
    //        }
    //        if (msg.what == 2) {
    //            Toast.makeText(InformationActivity.this,
    //                    "上传头像成功！", Toast.LENGTH_SHORT).show();
    //            try {
    //                JSONObject userJson = new JSONObject(
    //                        result.getData());
    //                CacheUrlPicture.downloadPicture(
    //                        userJson.getString("avatar"), InformationActivity.this,
    //                        false);
    //
    //            } catch (Exception e) {
    //                e.printStackTrace();
    //            }
    //        }
    //        if (msg.what == 3) {
    //            Toast.makeText(InformationActivity.this,
    //                    "上传头像失败！", Toast.LENGTH_SHORT).show();
    //        }
    //        if (msg.what == 4) {
    //            new AlertDialog.Builder(InformationActivity.this)
    //                    .setMessage("访问服务异常")
    //                    .setPositiveButton("确定", null).show();
    //        }
    //    }
    //
    //    ;
    //};

    private void getBitMap(String url) {
        new BitMapThread(url).start();
    }

    private void getBitMap(Bitmap bitmap) {
        new BitMapThread(bitmap).start();
    }

    private class BitMapThread extends Thread {
        private String avatarUrl;
        private Bitmap bitmap;

        public BitMapThread(String url) {
            this.avatarUrl = url;
        }

        public BitMapThread(Bitmap bitmap) {
            this.bitmap = bitmap;
        }

        @Override
        public void run() {
            try {
                if (bitmap == null) {
                    URL url = new URL(avatarUrl);
                    bmp = BitmapFactory.decodeStream(url.openConnection()
                            .getInputStream());
                    Message msg = new Message();
                    msg.what = 1;
                    //bitMapHander.sendMessage(msg);
                } else {
                    bmp = bitmap;
                    Message msg = new Message();
                    msg.what = 1;
                    //bitMapHander.sendMessage(msg);
                }
            } catch (Exception e) {
                Log.e("AccountFragment",
                        "in Thread,BitMapThread run function  error "
                                + e.getMessage());
            }
        }

    }

    public String bitmaptoString(Bitmap bitmap) {


        // 将Bitmap转换成字符串

        String string = null;

        ByteArrayOutputStream bStream = new ByteArrayOutputStream();

        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);

        byte[] bytes = bStream.toByteArray();

        string = Base64.encodeToString(bytes, Base64.DEFAULT);

        return string;

    }

    // 为头像弹出窗口实现监听类
    private final View.OnClickListener itemsOnClick = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    // 调用系统相机
                    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    // 指定调用相机拍照后照片的储存路径
                    //camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                    startActivityForResult(camera, 100);
                    break;
                case R.id.btn_pick_photo:
                    // 调用系统图库
                    Intent picture = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(picture, 101);
                    break;
                default:
                    break;
            }

        }

    };


    protected View findViewById(int id) {
        return view.findViewById(id);
    }
}
